package client;

import java.io.*;
import java.net.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import shared.CallObject;

public class Client {
	// private static ArrayList<String> callObject;
	private static BufferedReader keyboardreader;
	public static final int COMMAND_POS = 0;
	public static final int NAME_POS = 1;
	public static final int PW_POS = 2;
	private static CallObject sendObject;
	private static CallObject recieveObject;
	private static String name;
	private static String certPwd;
	private static String keystorePwd;

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws IOException {
		keyboardreader = new BufferedReader(new InputStreamReader(System.in));
		login();

		char[] passphraseKS = keystorePwd.toCharArray(); // lösenord för
															// keystore
		char[] passphraseTS = "truststore".toCharArray(); // lösenord för
															// truststore
		char[] passphraseCertifiate = certPwd.toCharArray(); // lösenord för
																// certifikatet
		String password = "client"; // lösenord för system.setproperty
		String filename = "/h/d3/x/ada10man/EDA040-Project/Hospital/Hospital/";

		SSLSocketFactory sf = null;
		try {

			// System.setProperty("javax.net.ssl.trustStore", filename
			// + "patient1.ts");
			// System.setProperty("javax.net.ssl.trustStorePassword", password);
			// VAD GÖR DESSA RADER..? VARFÖR FÅR VI "peer not authenticated"??

			KeyStore ks;
			ks = KeyStore.getInstance("JKS");
			ks.load(new FileInputStream(filename + name + ".jks"), passphraseKS);

			KeyManagerFactory kmf;
			kmf = KeyManagerFactory.getInstance("SunX509");
			kmf.init(ks, passphraseCertifiate);
			// FOR RECIEVING KEYS IN KEYSTORE

			KeyStore ts;
			ts = KeyStore.getInstance("JKS");
			ts.load(new FileInputStream(filename + name + ".ts"), passphraseTS);

			TrustManagerFactory tmf;
			tmf = TrustManagerFactory.getInstance("SunX509");
			tmf.init(ts);

			SSLContext context;
			context = SSLContext.getInstance("TLS");
			context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

			sf = context.getSocketFactory();

		} catch (Exception e) {
			e.printStackTrace();

		}

		try {
			SSLSocket socket = (SSLSocket) sf.createSocket("localhost", 1050);
			socket.setNeedClientAuth(true);

			socket.startHandshake();
			SSLSession session = socket.getSession();

			HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket,
					session);
			byte[] id = session.getId();
			ObjectOutputStream writer = new ObjectOutputStream(
					socket.getOutputStream());
			ObjectInputStream reader = new ObjectInputStream(
					socket.getInputStream());

			do {
				recieveObject = (CallObject) reader.readObject();
				System.out.println("recieveObject: "
						+ recieveObject.getText1());

				sendObject = chooseCommand();
				writer.writeObject(sendObject);
			} while (sendObject.getCommand() != 9);
			// TODO: 9 FINNS INTE.. ändra detta sen!!
			socket.close();

		} catch (Exception err) {
			System.err.println(err);
		}
	}


	private static CallObject chooseCommand() throws IOException {
		System.out.println("chose a command and press enter \n"
				+ "VIEW_RECORDS = 3, \n"
				+ "SAVE_RECORD = 4, \n" + "CREATE_RECORD = 5, \n"
				+ "DELETE_RECORD = 6, \n");
		int command = Integer.parseInt(keyboardreader.readLine());
		sendObject = new CallObject(command, null, null);

		switch (command) {
		case CallObject.SAVE_RECORD:
			System.out.println("record nbr");
			sendObject.setText1(keyboardreader.readLine());

			System.out.println("information to be added:");
			sendObject.setText2(keyboardreader.readLine());
			break;

		case CallObject.CREATE_RECORD:
			System.out.println("name of patient");
			sendObject.setText1(keyboardreader.readLine());

			System.out.println("name of nurse:");
			sendObject.setText2(keyboardreader.readLine());
			break;

		case CallObject.DELETE_RECORD:
			System.out.println("record nbr to delete");
			sendObject.setText1(keyboardreader.readLine());
		default:
		}
		return sendObject;

	}

	private static void login() throws IOException {
		System.out.println("name:");
		name = keyboardreader.readLine();
		System.out.println("certificate password:");
		certPwd = keyboardreader.readLine();
		System.out.println("keystore password:");
		keystorePwd = keyboardreader.readLine();
	}
}
